package com.zhyz.bookstore.servlet;

import com.zhyz.bookstore.entity.Admin;
import com.zhyz.bookstore.entity.Book;
import com.zhyz.bookstore.entity.Category;
import com.zhyz.bookstore.entity.User;
import com.zhyz.bookstore.service.ManagerService;
import com.zhyz.bookstore.service.impl.ManagerServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 后台管理servlet
 */
@WebServlet(name = "ManagerServlet", value = "/admin/ManagerServlet")
public class ManagerServlet extends HttpServlet {
    private ManagerService managerService = new ManagerServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 得到传过来的请求
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String op = request.getParameter("op");

        switch (op) {
            case "login":
                //管理员登录
                login(request, response);
                break;
            case "layout":
                //管理员退出登录
                layout(request,response);
                break;
            case "addBookUI":
                addBookUI(request,response);
                break;
            case "addBook":
                try {
                    addBook(request,response);
                } catch (FileUploadException e) {
                    throw new RuntimeException(e);
                }
                break;
            case "addCategory":
                addCategory(request,response);
                break;
            case "category":
                getCategoryBook(request,response);
                break;
            case "editBookUI":
                editBookUI(request,response);
                break;
            case "editBook":
                editBook(request,response);
                break;
            case "delBook":
                delBook(request,response);
                break;
            case "categoryList":
                categoryList(request,response);
                break;
            case "editCategoryUI":
                editCategoryUI(request,response);
                break;
            case "editCategory":
                editCategory(request,response);
                break;
            case "delCategory":
                delCategory(request,response);
                break;
            case "addAdmin":
                addAdmin(request,response);
                break;
            case "managerInformation":
                managerInformation(request,response);
                break;
            case "managerPassword":
                managerPassword(request,response);
                break;
            case "findUsers":
                findUsers(request,response);
                break;
            case "delUser":
                delUser(request,response);
        }
    }

    private void delUser(HttpServletRequest request, HttpServletResponse response) {
        String user_id = request.getParameter("UserId");
        managerService.delUser(user_id);
        try {
            response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                    + "/img/duigou.png'/>修改成功！</div>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    //删除书籍类型
    private void delCategory(HttpServletRequest request, HttpServletResponse response) {
        String category_id = request.getParameter("CategoryId");
        managerService.delCategroy(category_id);
        try {
            response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='\" + req.getContextPath()\n" +
                    " + \"/img/duigou.png'/>删除成功！</div>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //修改书籍分类信息
    private void editCategory(HttpServletRequest request, HttpServletResponse response) {

        String category_id = request.getParameter("CategoryId");
        String category_name = request.getParameter("CategoryName");
        String category_desc = request.getParameter("CategoryDesc");
        Category category = new Category(category_id,category_name,category_desc);
        managerService.upCategory(category);
        try {
            response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                    + "/img/duigou.png'/>修改成功！</div>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //获取书籍分类信息
    private void editCategoryUI(HttpServletRequest request, HttpServletResponse response) {
        Category category = managerService.getCategory(request.getParameter("CategoryId"));
        request.setAttribute("category", category);
        try {
            request.getRequestDispatcher("/admin/editCategory.jsp").forward(request, response);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //获取书籍分类列表
    private void categoryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Category> categoryList = managerService.getAllCatrgory();
        request.setAttribute("categoryList", categoryList);
        request.getRequestDispatcher("/admin/categorysList.jsp").forward(request, response);
    }

    //删除书籍
    private void delBook(HttpServletRequest request, HttpServletResponse response) {
        String book_id = request.getParameter("BookId");
        managerService.delBook(book_id);
        try {
            response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                    + "/img/duigou.png'/>删除成功！</div>");
            editBook(request, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //编辑书籍
    private void editBook(HttpServletRequest request, HttpServletResponse response) {
        String book_id = request.getParameter("BookId");
        String book_name = request.getParameter("BookName");
        String book_author = request.getParameter("BookAuthor");
        String book_press = request.getParameter("BookPress");
        String book_desc = request.getParameter("BookDesc");
        double book_price = Double.parseDouble(request.getParameter("BookPrice"));
        String book_kunumber = request.getParameter("BookKunumber");
        managerService.upBook(book_id, book_name, book_author, book_press, book_desc, book_price, book_kunumber);
        try {
            response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                    + "/img/duigou.png'/>修改成功！</div>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 编辑书籍信息前获取书籍的信息回显
    private void editBookUI(HttpServletRequest request, HttpServletResponse response) {
        String book_id = request.getParameter("BookId");
        Book book = getBooks(book_id);
        List<Category> category = managerService.getAllCatrgory();
        HashMap map = new HashMap();
        map.put("book",book);
        map.put("category",category);
        request.setAttribute("map",map);
        try {
            request.getRequestDispatcher("/admin/editBook.jsp").forward(request, response);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void getCategoryBook(HttpServletRequest request, HttpServletResponse response) {
        List<Book> books = managerService.getCategoryBook(request.getParameter("cid"));
        List<Category> categoryList = managerService.getAllCatrgory();
        request.setAttribute("books",books);
        request.setAttribute("categoryList",categoryList);
        try {
            request.getRequestDispatcher("/admin/booksList.jsp").forward(request,response);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //添加书籍分类
    private void addCategory(HttpServletRequest request, HttpServletResponse response) {
        String category_name = request.getParameter("CategoryName");
        String category_desc = request.getParameter("CategoryDesc");
        Category category = new Category(UUID.randomUUID().toString(),category_name,category_desc);
        try {
            BeanUtils.populate(category,request.getParameterMap());
            managerService.addCategory(category);
            response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                    + "/img/duigou.png'/>添加成功！</div>");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
        //添加图书
    private void addBook(HttpServletRequest request, HttpServletResponse response) throws FileUploadException,IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart){
            throw new RuntimeException("表单上传类型有误");
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        List<FileItem> items = new ArrayList<FileItem>();
        items = sfu.parseRequest(request);
        Book book = new Book();
        for (FileItem item:items){
            if (item.isFormField()){
                processFormField(item,request,book);
            }else {
                processUplodFiled(item,request,book);
            }
        }
        System.out.println(book.getCategory().getCategoryId());
        managerService.addBooks(book);
        response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                + "/img/duigou.png'/>添加成功！</div>");
    }

    private void processUplodFiled(FileItem item, HttpServletRequest req, Book book) {
        try {
            // 存放路径：不要放在web-inf中
            // 01.获取存放文件的真实目录
//            String dirImages = getServletContext().getRealPath("/images");
            String dirImages = getServletContext().getRealPath("/img");
            // 02. 通过io存文件
            // 03. 生成文件名 （用户上传图片， 图片名可能重复）
            String FieldName = item.getFieldName();// 输入框的name值
            String name = item.getName();
            String fileType = name.substring(name.lastIndexOf(".") + 1);
            String fileName = UUID.randomUUID().toString();// 生成用不重复的文件名
            // 生成文件夹名
            Date time = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String strTime = simpleDateFormat.format(time);
            // path属性filename
            String path = strTime + File.separator + "books";// 存放到book对象中的路径
//            String path = "books";// 存放到book对象中
            String filename = fileName + "." + fileType;
            // fileDir：图片最终存在于fileDir
            File fileDir = new File(dirImages, path + File.separator + filename);
            // InputStream inputStream = item.getInputStream(); 从请求 对象中 通过流的方式
            // 把 上传的文件加载到 内存中 构建输出流
            File parentDir = new File(dirImages, path);// 父目录
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            book.setFileName(filename);
            book.setPath(path);

            InputStream inputStream = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(fileDir);
            int len = 0;
            while ((len = inputStream.read()) != -1) {
                fos.write(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void processFormField(FileItem item, HttpServletRequest request, Book book) {
        // item每一个item对象代表一个输入框
        // 01. 获取input输入框的 name 的值 根据规范 输入框 的name的取值， 与 javabean 中的 属性名一致

        try {
            String inputName = item.getFieldName();
            String inputValue = item.getString("UTF-8");
            if (inputName.equals("categoryId")){
                String categoryid = item.getString();
                System.out.println("CategoryId="+categoryid);
                Category category = managerService.getCategory(categoryid);
                System.out.println(category);
                book.setCategory(category);
            }else{
                BeanUtils.setProperty(book,inputName,inputValue);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    // 添加书籍前先获取所有分类
    private void addBookUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Category> categorys = managerService.getAllCatrgory();
        request.setAttribute("cs",categorys);
        request.getRequestDispatcher("/admin/addBook.jsp").forward(request, response);
    }

    //管理员退出登录
    private void layout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("admin");
        response.sendRedirect("/client/ClientServlet?op=category");
    }

    //管理员登录
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        Admin admin = managerService.login(username, password);
        if (admin.getUsername() != null && admin.getUsername() != "") {
            request.setAttribute("message", "登陆成功！");
            session.setAttribute("admin", admin);
            request.getRequestDispatcher("/admin/message.jsp").forward(request, response);
        } else {
            response.getWriter().write("无此用户，请联系管理员！！      <a href='/client/ClientServlet?op=category'>返回首页</a>");
        }
    }

    private  Book getBooks(String book_id){
        return managerService.getBooks(book_id);
    }

    //添加工作人员
    private void addAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String tel = request.getParameter("tel");
        Admin admin = new Admin(username, password, name, sex, tel);
        managerService.addAdmin(admin);
        response.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + request.getContextPath()
                + "/img/duigou.png'/>修改成功！</div>");
    }

    //修改管理员登录密码
    private void managerPassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String repassword = req.getParameter("repassword");

        managerService.managerPassword(username, password);
        resp.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + req.getContextPath()
                + "/img/duigou.png'/>修改成功！</div>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    //修改个人休息
    private void managerInformation(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String tel = req.getParameter("tel");
        managerService.managerInformation(username, name, sex, tel);
        HttpSession session = req.getSession();
        Admin admin = (Admin) session.getAttribute("admin");
        admin.setName(name);
        admin.setSex(sex);
        admin.setTel(tel);
        session.setAttribute("admin", admin);
        resp.getWriter().write("<div style='text-align: center;margin-top: 260px'><img src='" + req.getContextPath()
                + "/img/duigou.png'/>修改成功！</div>");

    }

    //用户信息管理
    private void findUsers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> list = managerService.findUsers();
        HttpSession session = req.getSession();
        session.setAttribute("users", list);
        req.getRequestDispatcher("/admin/managerUsers.jsp").forward(req, resp);
    }

}
